// tcp_server.go
package nettyTcp

import (
	"context"
	"fmt"
	"log"
	"net"
	"sync"
)

type NettyTcpServer struct {
	port     int
	listener net.Listener
	ctx      context.Context
	cancel   context.CancelFunc
	wg       sync.WaitGroup
}

func NewNettyTcpServer(port int) *NettyTcpServer {
	ctx, cancel := context.WithCancel(context.Background())
	return &NettyTcpServer{
		port:   port,
		ctx:    ctx,
		cancel: cancel,
	}
}

func (s *NettyTcpServer) Start() error {
	addr := fmt.Sprintf(":%d", s.port)
	listener, err := net.Listen("tcp", addr)
	if err != nil {
		return err
	}
	s.listener = listener

	log.Printf("TCP server started on port %d", s.port)

	for {
		select {
		case <-s.ctx.Done():
			return nil
		default:
			conn, err := listener.Accept()
			if err != nil {
				log.Printf("Accept error: %v", err)
				continue
			}

			s.wg.Add(1)
			go s.handleConnection(conn)
		}
	}
}

func (s *NettyTcpServer) handleConnection(conn net.Conn) {
	defer s.wg.Done()
	defer conn.Close()

	// 实现类似 ChannelPipeline 的处理链
	pipeline := NewPipeline()
	pipeline.AddHandler(NewStringDecoder())
	pipeline.AddHandler(NewStringEncoder())
	pipeline.AddHandler(NewTcpServerHandler())

	// 处理连接上的数据
	pipeline.Process(conn)
}

func (s *NettyTcpServer) Stop() {
	s.cancel()
	if s.listener != nil {
		s.listener.Close()
	}
	s.wg.Wait()
}

// StringDecoder implementation
type StringDecoder struct{}

func NewStringDecoder() *StringDecoder {
	return &StringDecoder{}
}

func (d *StringDecoder) Handle(ctx *HandlerContext, msg interface{}) error {
	// Placeholder for decoding logic
	return nil
}

// StringEncoder implementation
type StringEncoder struct{}

func NewStringEncoder() *StringEncoder {
	return &StringEncoder{}
}

func (e *StringEncoder) Handle(ctx *HandlerContext, msg interface{}) error {
	// Placeholder for encoding logic
	return nil
}

// TcpServerHandler implementation
type TcpServerHandler struct{}

func NewTcpServerHandler() *TcpServerHandler {
	return &TcpServerHandler{}
}

func (h *TcpServerHandler) Handle(ctx *HandlerContext, msg interface{}) error {
	// Placeholder for handling logic
	return nil
}
